package study.service.impl;

import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import study.mapper.UserMapper;
import study.pojo.User;
import study.service.UserService;
import study.util.SqlSessionFatoryUtils;

public class UserServiceImpl implements UserService {
    SqlSessionFactory factory = SqlSessionFatoryUtils.getSqlSessionFactory();

    /*
     * 登录
     * */
    public User login(String username,String password){
        //2.获得SqlSession
        SqlSession sqlSession = factory.openSession();

        //3.获取UserMapper
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);

        //4.调用方法
        User user = mapper.select(username, password);

        //释放资源
        sqlSession.close();

        return user;
    }

    /*
    * 注册方法
    * */

    public boolean register(User user){
        //2.获取Sqlsession
        SqlSession sqlSession = factory.openSession();

        //3.获取UserMapper
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);

        //4.判断用户是否存在
        User u = mapper.selectByUsername(user.getUsername());


        if(u==null){
            //用户名不存在
            mapper.add(user);
            //提交事务
            sqlSession.commit();
        }

        //释放资源
        sqlSession.close();
        //用户名存在
        return u==null;
    }
    /*
     * 查询用户名是否存在
     * */

    public boolean selectUser(String username){
        //2.获取Sqlsession
        SqlSession sqlSession = factory.openSession();

        //3.获取UserMapper
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);

        //4.判断用户是否存在
        User u = mapper.selectByUsername(username);

        sqlSession.close();
        if(u==null){
            //用户名不存在
            return false;
        }else {
            //用户名存在
            return true;
        }


    }
}
